import { useEffect, useState } from 'react'
import { Select, message, Cascader, Space, Button, Input, Modal, Form, DatePicker, Table, Pagination, Upload, Image } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { UploadFile } from 'antd/es/upload/interface';
import { repairList, repairDelete, repairDeleteall, repairstateList, repairstypeList, userinfoList, repairAdd } from '../apis/repairs/repairs'
import { buildingList } from "../apis/repairs/repairs";
import '../assets/scss/repair.scss'

const { RangePicker } = DatePicker;
interface DataType {
    id: number;
    username: string;
    typename: string;
    statename: string;
    content: string;
    addtime: string;
    images: Array<any>;
    address: string;
}
const { TextArea } = Input;
const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};

const Index = (): JSX.Element => {
    const [form] = Form.useForm();
    const [forms] = Form.useForm();
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [repairsList, setRepairsList] = useState([]);   //报修列表
    const [page, setpage] = useState(1)
    const [psize, setpsize] = useState(5)
    const [searchForm, setSearchForm] = useState({})
    const [total, settotal] = useState()
    const [modaljie, setModaljie] = useState({
        title: "",
        isModalOpen: false,
        repairsid: 0
    })
    const [fileLists, setFileLists] = useState<UploadFile[]>([])
    const [pictures, setPictures] = useState([]); //储存多张图片
    const [builList, setBuilList] = useState([])   //地址列表
    const [repairsTateList, setRepairsTateList] = useState([])   //故障类型列表
    const [repairsTypeList, setRepairsTypeList] = useState([])   //故障状态
    const [userinfoTypeList, setUserinfoTypeList] = useState([])   //故障状态
    let token = sessionStorage.getItem("token")
    const dateFormat = 'YYYY/MM/DD';
    const handleChange = (e: any) => {
        let { fileList } = e
        let arr: any = [];
        fileList.forEach((element: any) => {
            let { response } = element;
            if (response) {
                if ({ ...response }.errCode && { ...response }.errCode === 10000) {
                    arr.push({ status: 'done', url: "", thumbUrl: "", filename: response.data, oldfilename: response.data });
                }
            }
            else {
                arr.push(element);
                console.log(888, element);

            }
        })
        setPictures(arr)
        setFileLists(fileList)
    }

    const onChangeImgs: any = {
        action: process.env.REACT_APP_UP_IMG_URL,
        name: "file",
        listType: "picture",
        fileList: [...fileLists],
        headers: { "Authorization": token }
    }
    const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 16 } }
    // const buttonItemLayout = { wrapperCol: { span: 14, offset: 4 } }
    const columns: ColumnsType<DataType> = [
        {
            title: 'id',
            dataIndex: 'id',
            align: 'center'
        },
        {
            title: '故障类型',
            dataIndex: 'typename',
            align: 'center',
        },
        {
            title: '维修地址',
            dataIndex: 'address',
            align: 'center'
        },
        {
            title: '故障图片',
            dataIndex: 'images',
            align: 'center',
            render: (_: any, record: any) => (
                <div>
                    <Space size="middle">
                        {record.images.map((item: any) => (
                            <Image key={item.id} className='imagesurl' src={process.env.REACT_APP_IMG_URL + item.url} alt="" />
                        ))}
                    </Space>
                </div>
            )
        },
        {
            title: '故障描述',
            dataIndex: 'content',
            align: 'center'
        },
        {
            title: '维修状态',
            dataIndex: 'statename',
            align: 'center'
        },
        {
            title: '业主名称',
            dataIndex: 'username',
            align: 'center'
        }, {
            title: '维修日期',
            dataIndex: 'addtime',
            align: 'center'
        }, {
            title: '操作',
            dataIndex: '',
            align: 'center',
            render: (_: any, record: any) =>
            (
                <Space size="middle">
                    <Button type='primary' onClick={() => onClickRedact(record)}>编辑</Button>
                    <Button type='primary' onClick={() => onClickDelete(record.id)} danger>删除</Button>
                </Space>

            )
        }
    ];
    //报修列表
    const getrepairList = async () => {
        let res: any = await repairList({ page: page, psize: psize, ...searchForm })
        if (res && res.errCode === 10000) {
            setRepairsList(res.data.list)
            settotal(res.data.counts)
        }
    }
    //类型
    const getRepairstypeList = async () => {
        const res: any = await repairstypeList();
        if (res && res.errCode === 10000) {
            setRepairsTypeList(res.data.list)
        }
    }
    //用户类型
    const getUserinfoList = async () => {
        const res: any = await userinfoList();
        if (res && res.errCode === 10000) {
            setUserinfoTypeList(res.data.list)
        }
    }
    //楼栋列表
    const getBuildingList = async () => {
        const res: any = await buildingList();
        if (res && res.errCode === 10000) {
            setBuilList(res.data.list)
        }
    }
    //状态
    const getRepairstateList = async () => {
        const res: any = await repairstateList();
        if (res && res.errCode === 10000) {
            setRepairsTateList(res.data.list)
        }
    }

    useEffect(() => {
        getrepairList()
    }, [page, psize, searchForm])
    useEffect(() => {
        getBuildingList()
        getRepairstateList()
        getRepairstypeList()
        getUserinfoList()
    }, [])

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const getChange = (page: number, psize: number) => {
        setpage(page)
        setpsize(psize)
        if (page == 0) {
            setpage(1)
        }
    }
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const onClickDelete = async (id: number) => {
        let res: any = await repairDelete({ id: id })
        if (res && res.errCode === 10000) {
            getrepairList()
            message.success('删除成功');
        }
    }
    const onClickDeleteAll = async () => {
        // console.log(selectedRowKeys, 22);
        if (!selectedRowKeys) {
        console.log(selectedRowKeys, 22);
            let res: any = await repairDeleteall({ ids: selectedRowKeys })
            if (res && res.errCode === 10000) {
                getrepairList()
                message.success('删除成功');
            }
        } else {
            message.warning('请勾选');
        }
    }
    const onFinish = async (values: any) => {
        console.log(values.address.constructor === Array);
        if (values.address.constructor === Array) {
            values.address = values.address.join('')
        } else {
            values.address = values.address
        }
        let arr: any = [];
        let res: any
        if (modaljie.repairsid === 0) {
            res = await repairAdd(values)
        } else {
            pictures.forEach((element: any) => {
                if (element.repairsid) {
                    arr.push({ id: element.uid, repairsid: element.repairsid, url: element.name });
                }
                else {
                    arr.push({ url: element.filename });
                }
            });
            values.images = arr
            res = await repairAdd(values)
        }
        if (res && res.errCode === 10000) {
            message.success('修改成功');
            onCancel()
            getrepairList()
            console.log(res);
        }
    }
    const onClickRedact = (e: any) => {
        setModaljie({ ...modaljie, title: "修改故障报修", isModalOpen: true, repairsid: e.id })
        let arrs: any = []
        // let arr: any = []
        e.images.forEach((item: any) => {

            let filenames = item.url;
            let url = "http://estate.eshareedu.cn/estate/upload/" + filenames;
            arrs.push({ status: 'done', thumbUrl: url, name: filenames, type: "image/jpeg", uid: item.id, repairsid: item.repairsid });
            setPictures(arrs)
            setFileLists(arrs)
        });
        form.setFieldsValue(e);
    }
    const onCancel = () => {
        form.resetFields();
        setPictures([])
        setModaljie({ ...modaljie, isModalOpen: false, repairsid: 0 })
    }
    const onSearch = (values: any) => {
        if (values.begindate != undefined) {
            values.enddate = values.begindate[1].format('YYYY-MM-DD')
            values.begindate = values.begindate[0].format('YYYY-MM-DD')
        }
        console.log(values);
        setSearchForm(values)
    }
    return (<div className='repair'>
        <div className="repheader">
            <div className='reptitle'>故障报修列表</div>
        </div>
        <div className="con">
            <Form
                {...formItemLayout}
                layout="inline"
                form={forms}
                onFinish={onSearch}
                labelWrap={true}
                className='Form'>
                <Form.Item label="报修标题" name="key">
                    <Input placeholder="报修标题" />
                </Form.Item>
                <Form.Item label="地址" name="address">
                    <Input placeholder="地址" />
                </Form.Item>
                <Form.Item label="电话" name="tel">
                    <Input placeholder="电话" />
                </Form.Item>
                <Form.Item label="按时间查询" name="begindate"  >
                    <RangePicker format={dateFormat} />
                </Form.Item>
                <Form.Item label="维修状态" name="state">
                    <Select style={{ width: 165, marginLeft: 4 }} placeholder="请选择">
                        {
                            repairsTateList.map((item: any) => (
                                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item label="维修类型" name="type">
                    <Select style={{ width: 165, marginLeft: 4 }} placeholder="请选择">
                        {
                            repairsTypeList.map((item: any) => (
                                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item label="居民" name="userid" >
                    <Select style={{ width: 165, marginLeft: 4 }} placeholder="请选择">
                        {
                            userinfoTypeList.map((item: any) => (
                                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
                    <Button htmlType="submit" type="primary">查询</Button>
                </Form.Item>

            </Form>
        </div>
        <div className="center">
            <Button type='primary'
                onClick={() => onClickDeleteAll()} danger>批量删除</Button>
        </div>
        <div className="table">
            <Table
                pagination={false} bordered
                rowKey={(columns) => columns.id}
                rowSelection={rowSelection} columns={columns} dataSource={repairsList}>
            </Table>
        </div>
        <div className="paginat">
            <Pagination
                className='pagination'
                total={total}
                showTotal={(total) => `共 ${total} 条`}
                defaultPageSize={psize}
                defaultCurrent={1}
                onChange={getChange}
                showQuickJumper
                showSizeChanger pageSizeOptions={[5, 10]}
            />
        </div>
        <Modal destroyOnClose={true} title={modaljie.title} centered
            width={600} footer={null} open={modaljie.isModalOpen} onCancel={onCancel}>
            <Form
                {...layout}
                form={form}
                name="control-hooks"
                onFinish={onFinish}
                style={{ maxWidth: 300 }}
            >
                <Form.Item name="address" label="修改地址">
                    <Cascader placeholder="请选择"
                        fieldNames={{ label: 'name', value: 'name', children: 'children' }}
                        options={builList} />
                </Form.Item>
                <Form.Item name="state" label="故障类型">
                    <Select style={{ width: 165, marginLeft: 4 }}>
                        {
                            repairsTateList.map((item: any) => (
                                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                            ))
                        }

                    </Select>
                </Form.Item>
                <Form.Item name="userid" label="业主名称">
                    <Select style={{ width: 165, marginLeft: 4 }}>
                        {
                            userinfoTypeList.map((item: any) => (
                                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item name="tel" label="电话">
                    <Input />
                </Form.Item>
                <Form.Item name="type" label="状态">
                    <Select style={{ width: 165, marginLeft: 4 }}>
                        {
                            repairsTypeList.map((item: any) => (
                                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item name="content" label="故障描述">
                    <TextArea rows={4} />
                </Form.Item>
                <Form.Item name="images" label="故障图片">
                    <Upload
                        {...onChangeImgs}
                        onChange={handleChange}>
                        <Button>点击上传</Button>
                    </Upload>
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Space size={10}>
                        <Button type="primary" htmlType="submit" size="small">提交</Button>
                        <Button onClick={onCancel} size="small">取消</Button>
                    </Space>
                </Form.Item>
            </Form>
        </Modal>
    </div>
    );
}
export default Index;